package com.wzy.orderSystem.service.impl;

import com.wzy.orderSystem.dao.FoodDao;
import com.wzy.orderSystem.pojo.admin;
import com.wzy.orderSystem.service.opAdmin;

import java.sql.Timestamp;
import java.util.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class opAdminImpl implements opAdmin {
    @Override
    public List<admin> selectById(int id) throws SQLException {
        ArrayList<admin> admins = new ArrayList<>();
        ResultSet resultSet = null;
        try {
            String sql = "SELECT * FROM admin WHERE id = ?";
            Object[] obj = {id};
            resultSet = FoodDao.selectByArgs(sql, obj);
            while(resultSet.next()){
                admin admin = new admin();
                int adId = resultSet.getInt(1);
                String userName = resultSet.getString(2);
                String password = resultSet.getString(3);
                Date lastLogin = resultSet.getDate(4);
                String nickName= resultSet.getString(5);
                String avatar = resultSet.getString(6);
                String token = resultSet.getString(7);

                admin.setId(adId);
                admin.setUsername(userName);
                admin.setPassword(password);
                admin.setLastLogin(lastLogin);
                admin.setNickname(nickName);
                admin.setAvatar(avatar);
                admin.setToken(token);

                admins.add(admin);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            resultSet.close();
        }
        return admins;
    }

    @Override
    public int updateById(int id, String password) {
        int rows = 0;
        String sql = "UPDATE `admin` SET password=? WHERE id=?";
        Object[] obj = {password,id};
        rows = FoodDao.updateByArgs(sql, obj);
        return rows;
    }

    @Override
    public int deleteById(int id) {
        int rows = 0;
        String sql = "DELETE FROM `admin` WHERE id=?";
        Object[] obj = {id};
        rows = FoodDao.updateByArgs(sql, obj);
        return rows;
    }

    @Override
    public int insertAdmin(int id, String username, String password, Date lastLogin,String nickName,String avatar,String token) {
        int rows = 0;
        String sql = "INSERT INTO `orderfood`.`admin` (`id`, `username`, `password`, `lastlogin`, `nickname`, `avatar`, `token`) VALUES (?, ?, ?, ?, ?, ?, ?)";
        Object[] obj = {id,username,password,new Timestamp(lastLogin.getTime()),nickName,avatar,token};
        rows = FoodDao.updateByArgs(sql, obj);
        return rows;
    }
}
